package com.stt.experiment.trynetty.server.handler;

import com.stt.experiment.trynetty.buffer.RequestBuffer;
import com.stt.experiment.trynetty.server.RequestManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 默认消息处理器
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame>{

    @Autowired
    private RequestManager requestManager;

    // 心跳信息，可移到constants文件
    private static final String HEART_BEAT = "heart_beat";

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame frame) throws Exception {
        String res = null;
        if (frame instanceof TextWebSocketFrame) {
            // 获取请求消息内容
            String requestContent = ((TextWebSocketFrame) frame).text();
            // if 心跳消息
            if (HEART_BEAT.equalsIgnoreCase(requestContent)) {
                res = requestContent;
            } else {
                // else 其他请求则请求分发
                RequestBuffer buffer = new RequestBuffer(channelHandlerContext.channel(), requestContent);
                requestManager.doRequest(buffer);
            }
        } else {
            log.warn("unsupport dataType: {}", frame.getClass().getName());
        }
        if (null != res) {
            channelHandlerContext.writeAndFlush(new TextWebSocketFrame(res));
        }
    }
}
